package com.example.ricebibackend.controller;

import com.example.ricebibackend.common.utils.JacksonUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Profile({"dev"})
@RestController
@RequestMapping("/task")
public class TaskController {
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 添加任务
     */
    @GetMapping("/add")
    public void add(String name) {
        logger.info("TaskController add(String name)接收到参数:{}", JacksonUtil.writeValueAsString(name));
        // 提交给线程池进行处理
        CompletableFuture.runAsync(() -> {
            System.out.println(name + "正在被" + Thread.currentThread().getName() + "处理");
            try {
                Thread.sleep(600000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPoolExecutor);
    }

    /**
     * 查看线程池内部情况
     */
    @GetMapping("/show")
    public String show() {
        logger.info("TaskController show()");
        long totalTaskCount = threadPoolExecutor.getTaskCount(); // 任务总数
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount(); // 已经完成的任务数
        int queueSize = threadPoolExecutor.getQueue().size(); // 任务队列长度
        int activeCount = threadPoolExecutor.getActiveCount(); // 活跃线程数
        Map<String, Object> map = new HashMap<>();
        map.put("已完成任务数", completedTaskCount);
        map.put("任务总数", totalTaskCount);
        map.put("正在活跃的线程数", activeCount);
        map.put("任务队列长度", queueSize);
        return JacksonUtil.writeValueAsString(map);
    }

}
